package cn.rkylin.oms.common.event;

import cn.rkylin.oms.common.event.message.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

import static com.google.common.collect.Maps.newEnumMap;

public class ReadyEvents {

    private static final Logger logger = Logger.getLogger(ReadyEvents.class);

    @Autowired
    private EventBusManager eventBusManager;

    /**
     *
     * How to use it? the following is an example.
     *
     *<pre>
     *{@code
     * @AutoWired
     * private ReadyEvents readyEvents;
     * ......
     * readyEvents.dispatchMessageEvent(
     *         EventTypeCodeEnum.AFTER_ORDER_SPLIT_FAILED,
     *         MessageReceiverBuilder.builder()
     *                 .user("e6dbc4f4b2b04feab645cc33eac7b6bf")
     *                 .role("3fdfds897fd9898kls77wcnnbd8skwfd")
     *                 .build(),
     *         ImmutableMap.<MessageTemplateVariable, Object>builder()
     *                  .put(MessageTemplateVariable.PROJECT, "project name")
     *                  .put(MessageTemplateVariable.COMPANY, "company name")
     *                  .build()
     * );
     *}
     * </pre>
     *
     * @param type this is an event type
     * @param receivers receiver collection, tell the event dispatcher who will receive it
     * @param variables this is a variable map, will using it with message template to generate the message content.
     */
    public void dispatchMessageEvent(EventTypeCodeEnum type, List<MessageReceiver> receivers, Map<MessageTemplateVariable, Object> variables) {
        try {
            eventBusManager.fireEvent(new MessageEvent(type, receivers, retrieveMessageDefinition("FIXED_CODE"), newEnumMap(variables)));
        } catch (Exception e) {
            logger.warn(String.format("fire event [%s] failed", type.name()));
        }
    }

    private MessageDefinition retrieveMessageDefinition(String messageCode) {
        // TODO this message definition will retrieve out from database.
        MessageDefinition definition = new MessageDefinition();
        definition.setCode(messageCode);
        definition.setSendWay(SendWay.EMAIL);
        definition.setRetryCount(3);
        definition.setRetryInterval(3);
        definition.setTitle("分单失败提醒");
        definition.setTemplate("{RECEIVER}你好：店铺：{SHOP}，存在无法分单的商品：{OTHERS}，请及时处理。详见：项目设置 -> 分单规则。相关订单号：{ORDER_ID}");
        definition.setEnabled(true);
        return definition;
    }

}
